/**
 * AnalyzeColorBitmap
 * 
 * 20/11/2013
 * 
 * Copyright GPL
 */
package com.jtmproject.classes;

import android.graphics.Bitmap;
import android.graphics.Color;

/**
 * This class analyzes the quantity of primary color in an image passed by
 * parameters
 * 
 * @author Javier Tejedor
 */
public class AnalyzeColorBitmap {

	private static final int TOTAL_PERCENTAGE = 100;
	private static final int MAX_QUANTITY_COLOR = 255;
	private float percentageRed;
	private float percentageBlue;
	private float percentageGreen;
	
	/**
	 * constructor
	 * @param bitmap
	 */
	public AnalyzeColorBitmap(Bitmap bitmap) {
		analyze(bitmap);
	}
	
	/**
	 * this does the analysis
	 * @param bitmap
	 */
	private void analyze(Bitmap bitmap){
		int pixelsX = bitmap.getWidth();
		int pixelsY = bitmap.getHeight();
		long accumulatorRed = 0;
		long accumulatorBlue = 0;
		long accumulatorGreen = 0;
		int pixel = 0;
		long totalPixelsColorMax = 0;
		
		for(int i = 0; i < pixelsY; i++){
			for(int x = 0; x < pixelsX; x++){
				pixel = bitmap.getPixel(x, i);
				accumulatorRed += Color.red(pixel);
				accumulatorBlue += Color.blue(pixel);
				accumulatorGreen += Color.green(pixel);
			}
		}
		
		totalPixelsColorMax = pixelsX * pixelsY * MAX_QUANTITY_COLOR;
		
		calculatePercentages(
				accumulatorRed, 
				accumulatorBlue, 
				accumulatorGreen, 
				totalPixelsColorMax);
	}
	
	/**
	 * This calculate the percentages
	 * @param accumulatorRed
	 * @param accumulatorBlue
	 * @param accumulatorGreen
	 * @param totalPixelsColorMax
	 */
	private void calculatePercentages(
			long accumulatorRed, 
			long accumulatorBlue,
			long accumulatorGreen, 
			long totalPixelsColorMax) {
				
		percentageRed = 
				(accumulatorRed * TOTAL_PERCENTAGE) / totalPixelsColorMax;
		percentageBlue = 
				(accumulatorBlue * TOTAL_PERCENTAGE) / totalPixelsColorMax;
		percentageGreen = 
				(accumulatorGreen * TOTAL_PERCENTAGE) / totalPixelsColorMax;
		
	}

	/**
	 * returns the percentage of red color
	 * @return
	 */
	public float getPercentageRed() {
		return percentageRed;
	}

	/**
	 * returns the percentage of blue color
	 * @return
	 */
	public float getPercentageBlue() {
		return percentageBlue;
	}

	/**
	 * returns the percentage of green color
	 * @return
	 */
	public float getPercentageGreen() {
		return percentageGreen;
	}
	
}
